package com.ls.la;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class QueryMediaActivity extends Activity {
	/** Called when the activity is first created. */

	String dateArray[];
	LinearLayout layout;
	GridView gv;
	Bitmap bitmap1[];
	ContentResolver cr;
	ProgressDialog pd;
	MyAsyncTask myAsyncTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		cr = getContentResolver();
		Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				null, null, null, null);
		int cursorCount = cursor.getCount();
		bitmap1 = new Bitmap[cursorCount];
		dateArray = new String[cursorCount];

		layout = new LinearLayout(this);
		layout.setOrientation(1);
		gv = new GridView(getApplicationContext());
		gv.setNumColumns(3);
		myAsyncTask = new MyAsyncTask();
		myAsyncTask.execute(cursor);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub

		if (id == 1) {

			pd = new ProgressDialog(this);
			pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pd.setMessage("Loading Images");
		}
		return pd;
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			// return im.length;
			return bitmap1.length;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return bitmap1[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub

			View v;
			if (convertView == null) {
				LayoutInflater li = getLayoutInflater();

				v = li.inflate(R.layout.imageview, null);
				TextView tv = (TextView) v.findViewById(R.id.label);
				if (dateArray[arg0].equals("")) {
					tv.setText("Date:" + "No date Detected");
				} else {

					tv.setText("Date:" + dateArray[arg0]);
				}
				ImageView iv = (ImageView) v.findViewById(R.id.icon_image);
				iv.setImageBitmap(bitmap1[arg0]);
			} else {
				v = convertView;
			}
			return v;
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		unbindDrawables(layout);
		makeBitmapNull();
		System.gc();
	}

	private void makeBitmapNull() {
		for (int i = 0; i < bitmap1.length; i++) {

			if (bitmap1[i] != null) {
				bitmap1[i].recycle();
			}

		}

	}

	private void unbindDrawables(View view) {
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ViewGroup) {
			Log.v("DEST", view.getClass() + "");
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			if (!(view instanceof GridView)) {
				((ViewGroup) view).removeAllViews();
			} else {
				gv.removeAllViewsInLayout();
			}
		}
	}

	class MyAsyncTask extends AsyncTask<Cursor, Void, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			showDialog(1);
		}

		@Override
		protected String doInBackground(Cursor... cursor1) {
			// TODO Auto-generated method stub
			Cursor cursor = cursor1[0];
			int i = 0;
			while (cursor.moveToNext()) {

				String id = cursor.getString(cursor
						.getColumnIndex(MediaStore.Images.ImageColumns._ID));
				long idC = Long.parseLong(id);
				Uri newUri = ContentUris.withAppendedId(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, idC);

				try {
					Bitmap bitmap = MediaStore.Images.Media.getBitmap(cr,
							newUri);

					Bitmap compBit = Bitmap.createScaledBitmap(bitmap, 100,
							100, true);
					bitmap1[i] = compBit;

					bitmap.recycle();

				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				String date1 = cursor.getString(cursor
						.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));

				Long d = Long.parseLong(date1);
				Date date = new Date(d);
				DateFormat dataformat = DateFormat
						.getDateInstance(DateFormat.LONG);
				String s4 = dataformat.format(date);
				dateArray[i] = s4;

				i++;
			}

			return "COMPLETE";
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(String result) {
			pd.dismiss();
			// TODO Auto-generated method stub
			MyAdapter myAdapter = new MyAdapter();
			gv.setAdapter(myAdapter);
			layout.addView(gv);
			setContentView(layout);
		}

	}

}